<template>
  <div class="container">
    <star-nav-bar title="订单明细" style="background: #eff2f5" />
    <!-- 选择收货地址 -->
    <div class="address flex box">
      <div v-if="address.detail" class="detail">
        <h1>{{ address.detail }}</h1>
        <span style="font-size: 14px; color: #999">{{ address.consignee }} {{ address.phone }}</span>
      </div>
      <div v-else @click="openPopup" class="detail">
        <h1>选择收货地址</h1>
      </div>
      <van-icon name="arrow" size="16" @click="openPopup" />
    </div>
    <div class="delivery-container">
      <!-- 配送时间 -->
      <div class="delivery box">
        <div class="item immediately" :class="{ active: deliveryMode === 1 }" @click="deliveryMode = 1">
          <span>立即配送</span>预计{{ deliverytime }}送达
        </div>
        <div class="item appointment" :class="{ active: deliveryMode === 2 }" @click="deliveryMode = 2">
          <span>预约配送</span>
        </div>
      </div>
      <!-- 订单菜品列表 -->
      <div class="cart-list box">
        <div class="cart-item" v-for="item in cartList" :key="item.id">
          <img :src="item.image" />
          <div class="info">
            <h3 class="name">
              {{ item.name }}
            </h3>
            <span v-if="item.dishFlavor" style="color: #999; font-size: 12px"> 口味:{{ item.dishFlavor }} </span>
            <div class="amount">
              <span class="number">×{{ item.number }}</span>
              <span><i style="font-size: 12px">￥</i>{{ item.amount }}</span>
            </div>
          </div>
        </div>
      </div>
      <!-- 订单费用 -->
      <div class="expense-container box">
        <div class="expense">
          <div class="item">
            <h3>打包费</h3>
            <span>￥{{ parkAmount }}</span>
          </div>
          <div class="item">
            <h3>配送费</h3>
            <span>￥{{ deliveryAmount }}</span>
          </div>
        </div>
        <div class="total">
          <h1>总计</h1>
          <span>￥{{ totalComputed }}</span>
        </div>
      </div>
      <!-- 备注 -->
      <div class="remark-container">
        <van-cell-group inset>
          <van-field v-model="tablewareNumber" label="餐具(份)：" />
          <van-field v-model="remark" label="备注：" />
        </van-cell-group>
      </div>
    </div>

    <div class="payment">
      <div class="total">
        合计<i>￥</i><span>{{ totalComputed }}</span>
      </div>
      <div class="submit" @click="submitOrder">提交订单</div>
    </div>
  </div>
  <!-- 收货地址列表弹窗 -->
  <van-popup v-model:show="addressListPopup" round>
    <div style="height: 46px; line-height: 46px; font-weight: 600; text-align: center; background-color: #f5f5f5">
      选择收货地址
    </div>
    <div class="address-list" v-if="addressList.length">
      <div class="address-item" v-for="item in addressList" :key="item.id" @click="router.push('/my/address')">
        <div class="detail">
          <span>{{ item.isDefault ? '默认' : '' }}</span>
          {{ item.detail }}
        </div>
        <div class="consignee">
          <span>{{ item.consignee }}</span>
          <span>{{ item.sex === '1' ? '先生' : '女士' }}</span>
          <!-- <span>{{ item.phone ? phoneFormat(item.phone) : '' }}</span> -->
          <span>{{ phoneFormat(item.phone) }}</span>
        </div>
      </div>
    </div>
    <div class="address-list" v-else>
      <div class="add-address" @click="addHandle">添加收货地址</div>
    </div>
  </van-popup>
</template>
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useCartStore } from '@/stores'
import { getAddressAPI, getDefaultAddressAPI } from '@/api/address'
import type { AddressResultItem } from '@/types/address'
import { phoneFormat } from '@/utils/format'
import { useRouter } from 'vue-router'
import { submitOrderAPI } from '@/api/order'
import dayjs from 'dayjs'
const router = useRouter()
const { cartList, clearCart } = useCartStore()
// 默认地址
const address = ref({} as AddressResultItem)
const addressList = ref<AddressResultItem[]>([])
// 获取默认地址
const getDefaultAddress = async () => {
  try {
    const { data } = await getDefaultAddressAPI()
    address.value = data
  } catch (error) {
    console.log(error)
  }
}
// 获取地址列表
const getAddressList = async () => {
  try {
    const { data } = await getAddressAPI()
    addressList.value = data
  } catch (error) {
    console.log(error)
  }
}
// 收货地址弹窗
const addressListPopup = ref(false)
const openPopup = () => {
  addressListPopup.value = true
  getAddressList()
}

// 配送方式 1 立即 2 预约
const deliveryMode = ref(1)
// 预计送达时间
const deliverytime = computed(() => {
  // 获取当前时间
  const currentTime = new Date()

  const startTime = new Date(currentTime.getTime() + 30 * 60 * 1000)
  const endTime = new Date(currentTime.getTime() + 45 * 60 * 1000)

  // 提取并格式化开始时间的小时和分钟部分，对单位数补0
  const startTimeStr = `${startTime.getHours().toString().padStart(2, '0')}:${startTime.getMinutes().toString().padStart(2, '0')}`
  const endTimeStr = `${endTime.getHours().toString().padStart(2, '0')}:${endTime.getMinutes().toString().padStart(2, '0')}`

  return `${startTimeStr}-${endTimeStr}`
})
const estimatedDeliveryTime = computed(() => {
  const currentTime = new Date()
  const endTime = new Date(currentTime.getTime() + 45 * 60 * 1000)
  return dayjs(endTime).format('YYYY-MM-DD HH:mm:ss')
})
// console.log(estimatedDeliveryTime.value)

// 备注
const remark = ref('')
// 餐具数量(默认为1)
const tablewareNumber = ref(1)
// 餐具数量状态 默认为1 按餐量提供
const tablewareStatus = ref(1)
// 打包费
const parkAmount = ref(1)
// 配送费
const deliveryAmount = ref(1)
// 总计
const totalComputed = computed(() => {
  return cartList.reduce(
    (total, cartItem) => total + cartItem.amount * cartItem.number,
    parkAmount.value + deliveryAmount.value,
  )
})
// 提交订单
const submitOrder = async () => {
  const params = {
    businessId: cartList[0].businessId,
    addressBookId: address.value.id,
    remark: remark.value,
    estimatedDeliveryTime: estimatedDeliveryTime.value,
    deliveryStatus: deliveryMode.value,
    tablewareNumber: tablewareNumber.value,
    tablewareStatus: tablewareStatus.value,
    deliveryAmount: deliveryAmount.value,
    packAmount: parkAmount.value,
    amount: totalComputed.value,
  }
  try {
    const { data } = await submitOrderAPI(params)
    // console.log(data)
    clearCart()
    router.push({ path: '/order/detail', query: { orderId: data.id } })
  } catch (error) {
    console.log(error)
  }
}
// 添加收获地址
const addHandle = () => {
  router.push({ path: '/my/address/add' })
}
onMounted(() => {
  if (cartList.length === 0) {
    router.back()
  }
  getDefaultAddress()
})
</script>
<style scoped lang="scss">
:deep() {
  .van-field__label {
    width: 80px;
  }
}
.van-cell-group--inset {
  margin: 10px;
}
.van-popup {
  width: 90%;
}

.address {
  padding: 15px;
  justify-content: space-between;
  .detail {
    flex: 1;
  }
}
.delivery-container {
  flex: 1;
  overflow: auto;
}
.delivery {
  padding: 5px;
  font-size: var(--font-size-medium);
  .item {
    height: 30px;
    font-weight: var(--text-weight);
    display: flex;
    align-items: center;
    padding: 5px 10px;
    margin-bottom: 5px;
    border-radius: var(--box-radius);
    border: 1px solid #eff2f5;
    span {
      margin-right: 20px;
    }
  }
  .immediately {
    margin-top: 5px;
  }
  .active {
    color: #ff0000;
    border: 1px solid #ff0000;
  }
}
.cart-list {
  max-height: 180px;
  overflow: auto;
  display: flex;
  flex-direction: column;
  margin-bottom: 0;
  padding: 20px 15px;
  border-radius: 10px 10px 0 0;
  .cart-item {
    display: flex;
    margin-bottom: 10px;
  }
  img {
    width: 80px;
    height: 80px;
    object-fit: cover;
    border-radius: 5px;
  }
  .info {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    margin-left: 10px;
    .name {
      span {
        font-size: 12px;
        color: #999;
      }
    }
    .amount {
      font-size: var(--font-size-large);
      color: var(--red-text);
      display: flex;
      justify-content: space-between;
      .number {
        color: #333;
      }
    }
  }
}
.expense-container {
  padding: 15px 15px;
  border-radius: 0 0 10px 10px;
  .expense {
    font-size: var(--font-size-medium);
    .item {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
  }
  .total {
    font-size: 18px;
    font-weight: var(--text-weight);
    display: flex;
    justify-content: space-between;
  }
}
.remark-container {
  margin-bottom: 60px;
}
.address-list {
  padding: 15px;
}
.address-item {
  margin-bottom: 5px;
  padding-bottom: 5px;
  border-bottom: 1px solid #eee;
}
.add-address {
  text-align: center;
}
.payment {
  height: 40px;
  position: fixed;
  right: 0;
  left: 0;
  bottom: 0;
  font-size: var(--font-size-medium);
  display: flex;
  align-items: center;
  box-sizing: border-box;
  border-radius: 10px;
  color: var(--btn-color);
  margin: 10px;
  .total {
    height: 2em;
    flex: 1;
    border-radius: 10px 0 0 10px;
    padding: 5px 10px;
    background: #000;
    span {
      font-size: 20px;
    }
  }
  .submit {
    height: 2em;
    line-height: 2em;
    padding: 5px 10px;
    background: #ff0000;
    border-radius: 0 10px 10px 0;
  }
}
</style>
